<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 15-9-18
 * Time: 下午4:57
 */

class BuyController extends Controller {

    private $_title;
    private $_daytime;
    private $_daydate;

    public function init() {
        parent::init();
        $__now_time = $_SERVER['REQUEST_TIME'];
        $this->_daytime = date("Y-m-d h:i:s",$__now_time);
        $this->_daydate = date("Y-m-d",$__now_time);
    }

    public function indexAction(){
        define ( 'ITEM_PER_PAGE', 10 );
        global $_BuyStateCfg;
        $buy = new BuyModel();


        $orderbyTime= $this->_request->getParam('orderbyTime');
        $orderbyTime=empty($orderbyTime) ? '' :htmlspecialchars(trim($orderbyTime) , ENT_QUOTES ,'utf-8');


        $orderbyNum= $this->_request->getParam('orderbyNum');
        $orderbyNum=empty($orderbyNum) ? '' :htmlspecialchars(trim($orderbyNum) , ENT_QUOTES ,'utf-8');

        $orderByPrice= $this->_request->getParam('orderByPrice');
        $orderByPrice=empty($orderByPrice) ? '' :htmlspecialchars(trim($orderByPrice) , ENT_QUOTES ,'utf-8');

        $page= $this->_request->getParam('page');
        $page  = empty($page) ? 1 : (int) $page;

        $keyword= $this->_request->getParam('keyword');
        $keyword=empty($keyword) ? '' :htmlspecialchars(trim($keyword) , ENT_QUOTES ,'utf-8');


        $pageurl ="/buy/index";


        //拼接条件
        if(!empty($keyword)){
            $condition[] ="product.product_code like '%{$keyword}%'";
            $pageurl .="/keyword/".$keyword;
        }

        $condition[] ="`iq_inquiry`.`status` not in({$_BuyStateCfg['wait_audit']},{$_BuyStateCfg['cancel']})";
        $condition[] ="`product_cates`.`cate_name` <> '' and product_brands.brand_name <> ''";

        if(!empty($condition))
        {
            $where = implode('AND ', $condition);
        }else{
            $where = " 1=1 ";
        }


        $orderby = "update_time desc";

        //排序
        if(!empty($orderbyTime)){
            if($orderbyTime == 'ASC'){
                $orderby = "update_time ASC";
            }else{
                $orderby = "update_time desc";
            }

            $pageurl .="/orderbyTime/".$orderbyTime;
        }

        if(!empty($orderbyNum)){
            if($orderbyNum == 'ASC'){
                $orderby = "num ASC";
            }else{
                $orderby = "num desc";
            }
            $pageurl .="/orderbyNum/".$orderbyNum;

        }

        if(!empty($orderByPrice)){
            if($orderByPrice =='ASC'){
                $orderby = "price ASC";
            }else{
                $orderby = "price desc";
            }
            $pageurl .="/orderByPrice/".$orderByPrice;

        }



        $totalItems = $buy->getCountByWhere($where);

        // 获取分页开始
        $page = $this->_request->getParam ( "page", 1 );
        $itempage = $this->_request->getParam ( "itempage", 0 );

        $offset = ($page - 1) * ITEM_PER_PAGE;
        if ($offset >= $totalItems) {
            $page = ceil ( $totalItems / ITEM_PER_PAGE );
            $offset = ($page - 1) * ITEM_PER_PAGE;
        }
        if ($offset < 0) {
            $offset = 0;
            $page = 1;
        }
        if(!empty($page)){
            $pageurl .= "/page/%d";
        }


        $list = $buy->getPageListByWhere($page,ITEM_PER_PAGE, $where,$orderby);
        foreach($list as $key=>$val){
            $list[$key]['update_time'] = Tools::time2Units(time () - strtotime ( $val['update_time'] )) . "前";
        }
        $this->_view->list = $list;


        $links = Tools::createPage($pageurl, ITEM_PER_PAGE, $page, $totalItems, $target = '_self');

        $this->_view->links = $links;
        $this->_view->keyword = $keyword;
        $this->_view->orderbyTime = $orderbyTime;
        $this->_view->orderbyNum = $orderbyNum;
        $this->_view->orderByPrice = $orderByPrice;
        $this->_view->page = $page;
    }


    public function detailAction(){
        global $_BuyStartMean,$_BuyStateCfg;
        $this->_title ="牌号详情";
        $id = $this->_request->getParam("id",'0');
        $buy = new BuyModel();

        $detail = $buy->getListById("iq_inquiry.id=".$id);
        $detail['update_time'] = Tools::time2Units(time () - strtotime ( $detail['update_time'] )) . "前";

       if(!empty($detail['p_id']) || !empty($detail['worker_id'])){
           $url = _HTTP_CLOUD_HOST."/api/getPrice/getWorkerInfoByUserID?worker_id=".$detail['worker_id'];
           $worker = Tools::https_request($url,$data=array('v'=>'1'));
           $worker_info = json_decode($worker,true);
           $detail['realname'] =$worker_info['realname'];
           $detail['contacts'] =$worker_info['realname'];
           $detail['mobile'] =$worker_info['mobile'];
           $detail['phone'] =$worker_info['phone'];
           $detail['qq'] =$worker_info['qq'];
       }


        $this->_view->detail = $detail;
        $this->_view->title = $this->_title;
        $this->_view->_BuyStartMean = $_BuyStartMean;
        $this->_view->_BuyStateCfg = $_BuyStateCfg;
    }


    public function savebuyAction(){
        if($this->_request->isPost()){

            $Post = $this->_request->getPost();
            global $_BuyStateCfg,$_BidPurchaseCfg,$_SmsSendSwitch,$_SmsSendContent;

            $id = empty($Post['qid']) ? 0 : (int) $Post['qid'];
            $product_id = empty($Post['product_id']) ? 0 : (int) $Post['product_id'];
            $p_id  = empty($Post['p_id']) ? 0 : (int) $Post['p_id'];
            $content = empty($Post['content']) ? 0 :  $Post['content'];
            $price = empty($Post['price']) ? 0 :  $Post['price'];
            $num = empty($Post['num']) ? 0 : $Post['num'];
            $delivery_area = empty($Post['delivery_area']) ? 0 : $Post['delivery_area'];

            $RetData = array(
                'code' => '',
                'msg'  => '',
            );
            $user_info = $this->_session->offsetGet('loginInfo');

            if(empty($user_info)){
                $RetData = array(
                    'code' => '1',
                    'msg'  => '请您登录后再发布！',
                );
                echo json_encode($RetData);
                die();
            }
            $user = new UsersinvoiceModel();
            $where = "user_id='{$user_info['id']}' and is_default ='Y'";
            $conpany = $user->getRowByWhere($where);


            if(empty($id)){
                $RetData = array(
                    'code' => '2',
                    'msg'  => '非常抱歉，这个求购存在问题，请联系客服确认',
                );
                echo json_encode($RetData);
                die();
            }

            $buy = new BuyModel();
            $detail = $buy->getListById("iq_inquiry.id=".$id);



            $userq = $user->getRowByWhere("id='{$detail['business_id']}'");
            //判断是否相同用户操作
            if($user_info['id'] == $detail['user_id']){
                $RetData = array(
                    'code' => '3',
                    'msg'  => '非常抱歉，你不能操作自己求购的信息',
                );
                echo json_encode($RetData);
                die();
            }

            if(empty($price)){
                $RetData = array(
                    'code' => '4',
                    'msg'  => '非常抱歉，请严格填写报价信息。',
                );
                echo json_encode($RetData);
                die();
            }

            if(empty($num)){
                $RetData = array(
                    'code' => '5',
                    'msg'  => '非常抱歉，请严格填写报价信息',
                );
                echo json_encode($RetData);
                die();
            }

            if(empty($delivery_area)){
                $RetData = array(
                    'code' => '5',
                    'msg'  => '非常抱歉，请严格填写报价信息',
                );
                echo json_encode($RetData);
                die();
            }

            $data = array(
                'user_id'           => $user_info['id'],
                'business_id'       => $conpany['id'], //这里给客户报的默认公司ID
                'inquiry_id'        => $id,
                'organization_id'   => 1,
                'department_id'     => 1,
                'create_time'       => $this->_daytime,
                'create_uid'        => 1,
                'update_time'       => $this->_daytime,
                'update_uid'        => 1,
                'type'              => 'require',
                'product_id'        => $product_id,
                'delivery_area'     => $delivery_area,
                'num'               => $num,
                'price'             => $price,
                'remark'            => $content,
                'status' => $_BidPurchaseCfg['order'],
            );
            $quota = new QuotationModel();
            $quota->getDB()->beginTransaction();
            try {

                $isquotexist = $quota->getRowByWhere("user_id={$user_info['id']} and business_id='{$conpany['id']}' and inquiry_id='{$id}' and status <> '{$_BidPurchaseCfg['cancel']}'");
                if(!empty($isquotexist)){
                    throw new Exception("非常抱歉，你已报过相同的信息，你不能重复报价",6);
                }
                $res_id = $quota->add($data);

                if(!empty($p_id)){
                    $validate =array(
                        'id' =>  $p_id,
                        'mobile' =>   $conpany['moblie'],
                        'realname' => $conpany['realname'],
                        'business_name' => $conpany['business_name'],
                        'info' =>  $content,
                    );
                    $url = _HTTP_CLOUD_HOST."/api/Getprice/replyInquiry";
                    $prodcut = https_request($url,$validate);
                    $getlist = json_decode($prodcut,true);

                    if($getlist['status']  != 'success'){
                        throw new Exception("非常抱歉，报价不成功！",9);
                    }
                }

                //开始更新状态
                //todo 这里更新错误了应该更新求购表而不是更新求购意向单的状态
                if(!empty($res_id)){
                    if($detail['status'] == $_BuyStateCfg['audit']){
                        $buy = new BuyModel();
                        $buy->updateById($id,array('status'=>"{$_BuyStateCfg['Negotiate']}"));
                    }
                }

                if($_SmsSendSwitch['op_buy'] == 1){
                    $content = str_replace('%d1',$detail['product_name'],$_SmsSendContent['op_buy_c']);
                    $sms = new sendSmsJxt();
                    $sms->otherSend($userq['mobile'],$content);
                }

                if($res_id && $res_id>0){
                    $RetData = array(
                        'code' => '8',
                        'msg'  => '报价成功！请您耐心等待联系！',
                    );
                    echo json_encode($RetData);

                }
                $quota->getDB()->commit();
                unset($buy);
                unset($quota);
                die();
            }catch (Exception $e) {
                $quota->getDB()->rollBack();
                $retcode = array(
                    'code'=> $e->getCode(),
                    'msg'=>$e->getMessage(),
                );
                echo json_encode($retcode);die();
            }
        }
    }
}